package dd.prog2.exercises.set08;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;

public class WordFrequencyCounter {
	
	LinkedList<Word> ll = new LinkedList<Word>();
	static String location = "src\\song.txt";
	int lineCnt = 0;
	int wordCnt = 0;
	
	public void analyzeText(File textFile) {
		try {
			BufferedReader in = new BufferedReader(new FileReader(textFile));
			// Iterate through each line of the file
			while (true) {
				String currLine = in.readLine();
				if (currLine == null)
					break;
				analyzeLine(currLine);
			}
		} catch (IOException ex) {
			System.out.println("Error occurred while reading from "
					+ textFile.getAbsolutePath() + ":");
			System.out.println(ex);
		}
	}

	private void analyzeLine(String line) {
//		System.out.println(line);
		line = line.toLowerCase();
		StringTokenizer st = new StringTokenizer(line, " ,.?!()\"");
		lineCnt++; // line counter
		while(st.hasMoreElements()){ // more words in the line
			wordCnt++; // word counter
			String nextWord = (String)st.nextElement(); // get next word 
//			System.out.println(nextWord);
			if(ll.size() == 0) { // Word List is empty
				ll.add(new Word(nextWord)); // add first word
			} else {
				Iterator<Word> it = ll.iterator();
				boolean found = false; // flag to check if the word is in the list
				while(it.hasNext()){ // check all words
					Word tmp = it.next();
					if(tmp.getWord().equals(nextWord)){ // if next word is in the list
						tmp.setCount(); // inc counter for this word
						found = true; // word is found in the list
						break; // stop looking for the word
					}  
				}
				if(!found){ // word not in the list
					ll.add(new Word(nextWord)); // add to the list	
				}
			}
		}
		
	}

	public void printResults() {
		System.out.println("Lines: "+lineCnt+"\nWords: "+wordCnt);
		Collections.sort(ll);
		Iterator<Word> it = ll.iterator();
		boolean newline = false;
		while(it.hasNext()){
			Word tmp = it.next();
//			System.out.printf("%10s : %3d ", <word>, <number>);
			System.out.printf("%13s : %3d", tmp.getWord(), tmp.getCount());
			if(newline)
				System.out.println();
			newline = !newline;
		}
		System.out.println("\nWords used: "+ll.size());
	}

	public static void main(String[] args) {
		WordFrequencyCounter counter = new WordFrequencyCounter();
		counter.analyzeText(new File(location));
		counter.printResults();
	}
}